package cn.org.xwb.bookmall.user.controller;

import cn.org.xwb.bookmall.model.constant.AccountConst;
import cn.org.xwb.bookmall.model.po.Address;
import cn.org.xwb.bookmall.model.service.impl.AddressServiceImpl;
import cn.org.xwb.bookmall.user.annotation.IsLoginParam;
import cn.org.xwb.common.encrypt.annotation.des.DesEn;
import cn.org.xwb.common.encrypt.annotation.rsa.RsaDe;
import cn.org.xwb.common.encrypt.annotation.rsa.RsaDeParam;
import cn.org.xwb.common.encrypt.constant.EncryptConstant;
import cn.org.xwb.common.error.annotation.ServerErrorCatch;
import cn.org.xwb.common.model.vo.RespResult;
import cn.org.xwb.common.valid.annotation.nu.NotNull;
import cn.org.xwb.common.valid.annotation.nu.NotNullParam;
import cn.org.xwb.common.valid.annotation.str.StrNotNull;
import cn.org.xwb.common.valid.annotation.str.StrNotNullParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/address")
public class UserAddressController {

    @Autowired
    private AddressServiceImpl addressService;

    @GetMapping("/all")
    @ServerErrorCatch
    @NotNull
    @StrNotNull
    @RsaDe
    @IsLoginParam
    @DesEn
    public RespResult<Object> getAll(
            @RequestParam(AccountConst.ACCOUNT_PARAM_NAME)
            @StrNotNullParam @RsaDeParam
            String account,
            @RequestParam(EncryptConstant.DES_KEY_PARAM_NAME)
            @StrNotNullParam @RsaDeParam
            String desKey,
            @RequestParam("userId") @NotNull
            Long userId
    ) {
        List<Address> addresses = addressService.findFromCache(userId);
        if (Objects.isNull(addresses)) return RespResult.fail("获取收货地址列表失败");
        Collections.reverse(addresses);
        return RespResult.success("获取收货地址列表成功", addresses);
    }

    @PostMapping("/save")
    @ServerErrorCatch
    @NotNull
    @StrNotNull
    @RsaDe
    @IsLoginParam
    @Transactional
    public RespResult<Object> saveAddress(
            @RequestParam(AccountConst.ACCOUNT_PARAM_NAME)
            @StrNotNullParam @RsaDeParam
            String account,
            @RequestParam(value = "id",required = false)
            Long id,
            @RequestParam("userId") @NotNull
            Long userId,
            @RequestParam("name") @StrNotNullParam @RsaDeParam
            String name,
            @RequestParam("phone") @StrNotNullParam @RsaDeParam
            String phone,
            @RequestParam("province") @StrNotNullParam @RsaDeParam
            String province,
            @RequestParam("city") @StrNotNullParam @RsaDeParam
            String city,
            @RequestParam("county") @StrNotNullParam @RsaDeParam
            String county,
            @RequestParam("address") @StrNotNullParam @RsaDeParam
            String address,
            @RequestParam("idDefault") @NotNull
            Boolean idDefault
    ) {
        // 当前保存的收货地址设置为默认收货地址
        if (idDefault) {
            // 将全部收货地址设置为非默认收货地址
            int i = addressService.getBaseMapper().updateAddressIdDefault(userId);
        }
        int res = 0;
        // 收货地址编号为空，为新增收货地址
        if (Objects.isNull(id)) {
            // 收货地址信息对象
            Address address1 = new Address();
            address1.setUserId(userId); // 用户编号
            address1.setName(name); // 收货人姓名
            address1.setPhone(phone); // 收货人手机号
            address1.setProvince(province); // 收货地省份
            address1.setCity(city); // 收货地城市
            address1.setCounty(county); // 收货地区县
            address1.setAddress(address); // 收货详细地址
            address1.setIdDefault(idDefault); // 是否为默认收货地址
            // 新增收货地址
            res = addressService.getBaseMapper().insert(address1);
        }
        // 收货地址编号不为空，为修改收货地址
        else {
            // 收货地址信息对象
            Address address1 = new Address();
            address1.setId(id); // 收货地址编号
            address1.setUserId(userId); // 用户编号
            address1.setName(name); // 收货人姓名
            address1.setPhone(phone); // 收货人手机号
            address1.setProvince(province); // 收货地省份
            address1.setCity(city); // 收货地城市
            address1.setCounty(county); // 收货地区县
            address1.setAddress(address); // 收货详细地址
            address1.setIdDefault(idDefault); // 是否为默认收货地址
            // 修改收货地址
            res = addressService.getBaseMapper().updateById(address1);
        }
        // 保存收货地址失败
        if (res < 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RespResult.fail("保存收货地址失败");
        }
        List<Address> addresses = addressService.findAndCacheAll(userId);
        // 刷新缓存收货地址失败
        if (Objects.isNull(addresses)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RespResult.fail("保存收货地址失败");
        }
        // 保存收货地址成功
        return RespResult.success("保存收货地址成功");
    }

    @PostMapping("/del")
    @ServerErrorCatch
    @NotNull
    @StrNotNull
    @RsaDe
    @IsLoginParam
    @Transactional
    public RespResult<Object> delAddress(
            @RequestParam(AccountConst.ACCOUNT_PARAM_NAME)
            @StrNotNullParam @RsaDeParam
            String account,
            @RequestParam(value = "id") @NotNullParam
            Long id,
            @RequestParam("userId") @NotNull
            Long userId
    ) {
        boolean res = addressService.removeById(id);
        if (!res) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RespResult.fail("删除收货地址失败");
        }
        List<Address> addresses = addressService.findAndCacheAll(userId);
        if (Objects.isNull(addresses)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RespResult.fail("删除收货地址失败");
        }
        return RespResult.success("删除收货地址成功");
    }

}
